package com.hxj.user.service.impl;

import com.hxj.common.core.pojo.bo.RestResult;
import com.hxj.user.enums.CommonLoginFailReasons;
import com.hxj.user.pojo.bo.CommonUser;
import com.hxj.user.pojo.command.UserCommonLoginCommand;
import com.hxj.user.pojo.command.UserCommonRegisterCommand;
import com.hxj.user.pojo.dto.CommonLoginResultDto;
import com.hxj.user.pojo.dto.CommonRegisterResultDto;
import com.hxj.user.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.Optional;

/**
 * @Author hxj
 * @Date 2024/10/16 20:09
 * @Description
 */

@Slf4j
public abstract class UserCommonLoginServiceImpl implements UserLoginService {

    @Override
    public CommonRegisterResultDto register(UserCommonRegisterCommand registerCommand) {
        CommonRegisterResultDto resultDto = new CommonRegisterResultDto();
        try {
            RestResult<CommonUser> createUserResult = createUser(registerCommand);
            if (Objects.equals(createUserResult.getCode(), RestResult.success().getCode())) {
                resultDto.setSuccess(true);
                resultDto.setUser(createUserResult.getData());
            } else {
                resultDto.setSuccess(false);
                resultDto.setFailMessage(createUserResult.getMessage());
            }
        } catch (Throwable throwable) {
            resultDto.setSuccess(false);
            resultDto.setFailMessage("注册失败：" + throwable.getMessage());
            log.error("注册失败：", throwable);
        }

        return null;
    }

    protected abstract RestResult<CommonUser> createUser(UserCommonRegisterCommand registerCommand);

    @Override
    public CommonLoginResultDto login(UserCommonLoginCommand loginCommand) {
        CommonLoginResultDto resultDto = new CommonLoginResultDto();
        try {
            Optional<CommonUser> user = getUser(loginCommand);
            if (user.isPresent()) {
                resultDto.setSuccess(true);
                resultDto.setUser(user.get());
            } else {
                resultDto.setSuccess(false);
                resultDto.setFailReason(CommonLoginFailReasons.WRONG_USERNAME_PASSWORD);
            }
        } catch (Throwable throwable) {
            resultDto.setSuccess(false);
            resultDto.setFailReason(CommonLoginFailReasons.OTHER);
            resultDto.setFailMessage("登录失败：" + throwable.getMessage());
            log.error("登录失败：", throwable);
        }
        return resultDto;
    }

    protected abstract Optional<CommonUser> getUser(UserCommonLoginCommand loginCommand);

}
